/*
 * @Author: your name
 * @Date: 2022-01-05 12:39:46
 * @LastEditTime: 2022-01-05 13:52:15
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /socket/reback/server.cpp
 */
#include <stdio.h>  // printf
#include <string.h> // memset
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h> //socket
#include <netinet/in.h>// IPPROTO_TCP, sockaddr_in

const int BUFFER_SIZE = 100;
int main()
{
    // socket ctor
    int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //TCP/IP family, connection-based byte streams,  Exterior Gateway Protocol

    // bind IP and port with socket
    struct sockaddr_in serv_addr;
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    serv_addr.sin_port = htons(1234);
    bind(serv_sock,(struct sockaddr*)&serv_addr, sizeof(serv_addr));

    // listen status
    listen(serv_sock, 20);

    // accept request from cilent
    struct sockaddr_in clnt_addr;
    socklen_t clnt_addr_size = sizeof(clnt_addr);
    char str[BUFFER_SIZE] = {0};
    while (1)
    {
        int clnt_sock = accept(serv_sock, (struct sockaddr *)(&clnt_addr), &clnt_addr_size);

        // send data 2 cilent

        int strLen = recv(clnt_sock, str, BUFFER_SIZE, 0);
        // write(clnt_sock,str,sizeof(str));
        send(clnt_sock, str, strLen, 0);  // reback
        close(clnt_sock);
        memset(str,0,BUFFER_SIZE);  // reset buffer
    }

    //close socket
    close(serv_sock);

    return 0;
}